<?php
	session_start();
	header("Content-Type: text/html;charset=utf-8");
	if(isset($_POST['signinname'])){
		$username=$_POST['signinname'];
		$_SESSION['signinname']=$_POST['signinname'];
	}elseif(isset($_SESSION['signinname'])){
		$username=$_SESSION['signinname'];
	}else{
		echo "名字未设置！";
		exit();
	}
	if(!isset($_SESSION['qusername'])&&isset($_SESSION['keywords'])){//没有提交过名字并且有扫码
		if(!preg_match("/^[\x{4e00}-\x{9fa5}]+$/u",$username)) {
			echo "<script>alert('名字应该是中文');history.back(-1);</script>";
			exit();
		}
		if(mb_strlen($username,'utf-8')<2||mb_strlen($username,'utf-8')>6){
			echo "<script>alert('名字长度应该是2~6，你当前长度是".mb_strlen($username,'utf-8')."');history.back(-1);</script>";
			exit();
		}
		$code=$_SESSION['keywords'];
		//创建连接
		$conn = mysqli_connect("localhost", "root", "", "signin");
		mysqli_query($conn,"set names utf8");
		//检测连接
		if (!$conn){
			die("Connection failed:".mysqli_connect_error());
		}
		$eventname=$_SESSION['qevent'];
		$username = mysqli_real_escape_string($conn,$username);
		$sql1 = "SELECT * FROM persons WHERE event='$eventname' AND username='start'";
		$result1 = mysqli_query($conn, $sql1);
		if(!$row = mysqli_fetch_assoc($result1)){
			mysqli_close($conn);
			echo "事件“".$eventname."”不在签到时间范围内";
			exit();
		}
		$sql1 = "SELECT * FROM persons WHERE username='$username' AND event='$eventname'";
		$result1 = mysqli_query($conn, $sql1);
		if($row = mysqli_fetch_assoc($result1)){//该用户已存在
			if(isset($_SESSION['qevent'])&&$_SESSION['qevent']==$eventname){//用户在当前活动中已经签过到了
				mysqli_close($conn);
				echo $username."，您在".$eventname."的这次活动中已经签到过了！";
				exit();
			}
		}
		date_default_timezone_set('prc');//设置为北京时间
		$addtime = date("Y-m-d H:i:s",time());
		$sql = "INSERT INTO persons (username, code, add_time, event) 
		VALUES ('$username', '$code', '$addtime', '$eventname')";
		$result = mysqli_query($conn, $sql);
		mysqli_close($conn);
		$_SESSION['issignined']=1;
		$_SESSION['qusername']=$username;
		echo "<title>签到成功！</title>";
		echo "<center>";
		echo "<h1>".$_SESSION['qusername'].",您好，您已经成功签到了！</h1>";
		echo "</center>";
	}else{
		if(isset($_SESSION['qusername'])){
			echo "<center><h1>".$_SESSION['qusername'].",您好，您已提交请求</h1></center>";
		}else{
			echo "<center><h1>您已提交请求</h1></center>";
		}
	}
?>